package m202406.d20;

import java.util.ArrayList;
import java.util.List;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/20 21:33
 */
public class Q93 {

    public static void main(String[] args) {
        Q93 q93 = new Q93();
        q93.restoreIpAddresses("0000");
    }

    public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<>();
        dfs(s, 0, 0, new ArrayList<>(), res);
        return res;
    }

    private void dfs(String s, int start, int count, List<String> list, List<String> res) {
        if (count == 4) {
            res.add(String.join(".", list));
            return;
        }
        for (int i = start + 1; i <= Math.min((count + 1) * 3, s.length()); i++) {
            i = count == 3 ? s.length() : i;
            String temp = s.substring(start, i);
            if (!valid(temp)) {
                continue;
            }
            list.add(temp);
            dfs(s, i, count + 1, list, res);
            list.remove(list.size() - 1);
        }
    }

    private boolean valid(String s) {
        if ((s.length() > 1 && s.startsWith("0")) || s.length() > 3) {
            return false;
        }
        int i = Integer.parseInt(s);
        return i >= 0 && i <= 255;
    }
}
